package com.ksc.storekeeper.server.api.impl;

import java.util.List;

import org.springframework.security.crypto.password.PasswordEncoder;

import com.ksc.storekeeper.server.api.UserApi;
import com.ksc.storekeeper.server.entities.User;
import com.ksc.storekeeper.server.repositories.UserRepository;
import com.ksc.storekeeper.server.utils.AuthenticationUtil;
import com.ksc.storekeeper.shared.exceptions.ClientException;

public class UserApiImpl implements UserApi {

	private final UserRepository userRepository;
	private final PasswordEncoder encoder;

	public UserApiImpl(UserRepository userRepository, PasswordEncoder encoder) {
		this.userRepository = userRepository;
		this.encoder = encoder;
	}

	@Override
	public List<User> getAllUsers() {
		return userRepository.findAllUsers();
	}

	@Override
	public void addUser(User u) {
		u.setPassword(encoder.encode(u.getPassword()));
		userRepository.save(u);
	}

	@Override
	public void changePassword(String old, String newPass) throws ClientException {
		User current = AuthenticationUtil.getCurrentUser();
		if (!encoder.matches(old, current.getPassword())) {
			throw new ClientException("Invalid Old Password.");
		} else {
			current.setPassword(encoder.encode(newPass));
			userRepository.save(current);
		}
	}

	@Override
	public void changeRole(String userName, String role) throws ClientException {
		User usr = userRepository.findByUserName(userName);
		if (usr == null) {
			throw new ClientException("User doesn't exists");
		}
		usr.setAuthority(role);
		userRepository.save(usr);
	}

}
